package com.gome.ocean.controller.datax;

import java.io.IOException;
import java.net.URL;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.http.client.methods.HttpGet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.Page;
import com.gome.ocean.common.constants.Constants;
import com.gome.ocean.common.constants.DataxContants;
import com.gome.ocean.common.exception.DataxRemoteInvokeException;
import com.gome.ocean.common.utils.AddressUtils;
import com.gome.ocean.common.utils.HttpClientUtil;
import com.gome.ocean.common.utils.IOUtils;
import com.gome.ocean.common.utils.ResponsePage;
import com.gome.ocean.dao.model.datax.JobHistoryBO;
import com.gome.ocean.service.datax.JobHistoryService;

/**
 * Created by liuqingxia on 2016/2/22.
 */
@Controller
public class JobHistoryController {

    private static final Logger LOG = LoggerFactory.getLogger(JobHistoryController.class);
    @Autowired
    private JobHistoryService   jobHistoryService;

    @RequestMapping(value = "/job/history/find", method = RequestMethod.GET)
    public String queryGet() {
        return "job/history/find";
    }

    @RequestMapping(value = "/job/history/find", method = RequestMethod.POST)
    @ResponseBody
    public ResponsePage<JobHistoryBO> queryPost(HttpServletRequest req) {
        String jobIdStr = req.getParameter("jobId");
        String pageNumStr = req.getParameter("pageNum");
        String pageSizeStr = req.getParameter("pageSize");
        int pageNum = Constants.DEFAULT_PAGE_NUM;
        int pageSize = Constants.DEFAULT_PAGE_SIZE;
        Long jobId = null;
        ResponsePage<JobHistoryBO> page = new ResponsePage();
        if (StringUtils.isBlank(jobIdStr)) {
            return page.setErrorMsg("参数jobId不能为空");
        }
        if (!jobIdStr.matches(Constants.REG_NUMBER)) {
            return page.setErrorMsg("参数jobId不是数字格式");
        }
        jobId = Long.parseLong(jobIdStr.trim());
        if (!StringUtils.isBlank(pageNumStr)) {
            pageNum = Integer.parseInt(pageNumStr.trim());
        }
        if (!StringUtils.isBlank(pageSizeStr)) {
            pageSize = Integer.parseInt(pageNumStr.trim());
        }
        try {
            Page<JobHistoryBO> jobHistories = jobHistoryService.findJobHistoryByJobId(jobId, pageNum, pageSize);
            if (null == jobHistories || jobHistories.isEmpty()) {
                return page.emptyPage("没有查询到相关任务执行记录");
            }
            return page.setPage(jobHistories, "查询成功");
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return page.setErrorMsg("查询执行明细过程中发生异常，异常信息为：" + e.getMessage());
        }
    }

    /**
     * 获取任务执行LOG
     * 
     * @param jobId
     * @return
     */
    @RequestMapping(value = "/job/history/log/find", method = RequestMethod.POST)
    @ResponseBody
    public String getLogContext(Long historyJobId, Long beginIndex) {
        if (historyJobId == null || historyJobId.intValue() <= 0) return StringUtils.EMPTY;
        try {
            JobHistoryBO jobHistoryBO = jobHistoryService.findJobHistoryById(historyJobId);
            if (jobHistoryBO != null) {
                // 判断如果是本机执行的
                if (jobHistoryBO.getExecuteIp().equals(AddressUtils.getHostIp())) {
                    try {
                        return IOUtils.readLines(jobHistoryBO.getLogUrl());
                    } catch (IOException e) {
                        LOG.error("读取日志文件出错！logUrl:" + jobHistoryBO.getLogUrl());
                        return e.getMessage();
                    }
                } else {
                    if (StringUtils.isNotEmpty(jobHistoryBO.getExecuteIp())) {
                        String jobResource = DataxContants.getDataxConsoleLogPath(jobHistoryBO.getExecuteIp(),
                            jobHistoryBO.getId(),
                            beginIndex);
                        HttpClientUtil httpClientUtil = new HttpClientUtil();
                        try {
                            URL url = new URL(jobResource);
                            HttpGet httpGet = HttpClientUtil.getGetRequest();
                            httpGet.setURI(url.toURI());
                            return httpClientUtil.executeAndGetWithFailedRetry(httpGet, 6, 1000l);
                        } catch (Exception e) {
                            throw new DataxRemoteInvokeException("获取作业配置信息失败:" + jobResource, e);
                        }
                    }
                }
            }
        } catch (Exception e) {
            LOG.error(e.toString());
        }
        return StringUtils.EMPTY;
    }
}
